package utils

import (
	"math/rand"
	"time"
)

const (
	letterBytes   = "abcdefghijklmnopqrstuvwxyz0123456789"
	letterIdxBits = 6                    // 6 bits to represent a letter index
	letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
	letterIdxMax  = 63 / letterIdxBits   // # of letter indices fitting in 63 bits
)

var src = rand.NewSource(time.Now().UnixNano())
var randBytes = rand.New(src)

/*
 * @Description:
 * @File: RandName
 * @Version: 1.0.0
 * @Date: 2024/5/7 16:09
 * @Software: GoLand
 * @Author:fenglin
 */

// RandomName 生成一个指定长度的随机字符串
func RandomName(n int) string {
	b := make([]byte, n)
	// A rand.Int63() generates 63 random bits, enough for letterIdxMax characters!
	for i, cache, remain := n-1, randBytes.Int63(), letterIdxMax; i >= 0; {
		if remain == 0 {
			cache, remain = randBytes.Int63(), letterIdxMax
		}
		if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
			b[i] = letterBytes[idx]
			i--
		}
		cache >>= letterIdxBits
		remain--
	}

	return string(b)
}
